<?php

namespace app\api\service;

use think\Controller;
use think\Db;

class Registration extends Controller
{
	protected static $err_code = 0;

	// 签到接口
	public static function save_registration($param) {
		// 启动事务
		Db::startTrans();
		try {

		    $check_registration = self::check_registration(['member_id' => $param['member_id']]);
		    if ($check_registration['code'] != 200) {
		        throw new \Exception('已签到');
            }
			// 添加签到记录
			$data = ['member_id' => $param['member_id'], 'create_time' => strtotime(date('Y-m-d'))];
			model('registration')->save($data);

			$integral = 10; // 签到赠送积分数量

            // 签到成功 赠送积分
            $integral_data = ['member_id' => $param['member_id'], 'num' => $integral, 'msg' => '签到赠送'];
            model('integral_bill')->save($integral_data);

			// 更新用户表
			model('member')->where('id', $param['member_id'])->setInc('integral', $integral);

			// 提交事务
			Db::commit();
			return api_return(200, []);
		} catch (\Exception $e) {
			// 回滚事务
			Db::rollback();
			return api_return(0, [], $e->getMessage());
		}
	}

	// 检查当天是否已经签到接口接口
	public static function check_registration($param) {
		try {
			// 检查该用户是否已经签到，虽然前端会做判断，但是还是要以防万一
			$registration_time = strtotime(date('Y-m-d'));
			$check_registration = model('registration')->where('create_time', $registration_time)->where('member_id', $param['member_id'])->find();
			if ($check_registration) {
				throw new \Exception('已签到');
			}
			return api_return(200, []);
		}
		catch (\Exception $e)
		{
			return api_return(0, [], $e->getMessage());
		}
	}
}
